<template>
  <div >
<!--    <div class="title" style="display: flex;margin: 0 5px;">-->
<!--      <div style="flex:1;">-->
<!--        扫码装车（扫描销售单二维码）-->
<!--      </div>-->
<!--      <div style="padding-right: 10px;">-->
<!--        <lbtn @click="openSearch"> 手工找单</lbtn>-->
<!--      </div>-->
<!--    </div>-->
<!--    <div  class="order">-->
<!--      <t-grid size="large" :fields="columns" :data-list="orders" :showFooter="false" :offsetHeight="300"  />-->
<!--    </div>-->
<!--    &lt;!&ndash;    下面汇总及车辆信息选择&ndash;&gt;-->
<!--    <div style="margin-top: 5px;">-->
<!--      <div style=" display: flex;flex-direction: row;">-->
<!--        <div style="flex: 7">-->
<!--          <t-grid :fields="grpColumns" :data-list="grpData"   />-->
<!--        </div>-->
<!--        <div style="flex: 3;padding: 5px 0 20px;text-align: left;">-->
<!--          <div style="padding-left: 20px;font-size: 16px;font-weight: bolder;color: lightseagreen;">配送车辆：</div>-->
<!--          <div style="padding: 10px 0;color: #2b85e4;">-->
<!--            <div style="padding: 5px 0 0 15px;">-->
<!--              <table>-->
<!--                <tr>-->
<!--                  <td style="width: 60px; color: lightseagreen">车牌</td>-->
<!--                  <td style="padding: 3px">-->
<!--                    <ltext :height="35" placeholder="点击选择车辆" readonly @click="focusOn('carsId')" v-model="carModel.licence" />-->
<!--                  </td>-->
<!--                  <td style="padding-left: 5px;">-->
<!--                    <i class="fa fa-trash" @click="clearInput('carsId')" />-->
<!--                  </td>-->
<!--                </tr>-->
<!--                <tr>-->
<!--                  <td style="width: 60px;  color: lightseagreen;padding: 20px 0">驾驶员</td>-->
<!--                  <td style="padding: 3px">-->
<!--                    <ltext placeholder="点击选择驾驶员" readonly :height="35" @click="focusOn('driverId')"   v-model="carModel.driverName" />-->
<!--                  </td>-->
<!--                  <td style="padding-left: 5px;">-->
<!--                    <i class="fa fa-trash" @click="clearInput('driverId')" />-->
<!--                  </td>-->
<!--                </tr>-->
<!--                <tr>-->
<!--                  <td style="width: 60px;  color: lightseagreen">送货员</td>-->
<!--                  <td style="padding: 3px">-->
<!--                    <ltext placeholder="点击选择送货员" readonly :height="35" @click="focusOn('deliverIds')" v-model="carModel.deliverNames" />-->
<!--                  </td>-->
<!--                  <td style="padding-left: 5px;">-->
<!--                    <i class="fa fa-trash" @click="clearInput('deliverIds')" />-->
<!--                  </td>-->
<!--                </tr>-->
<!--              </table>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div style="flex: 2;padding: 20px;">-->
<!--          <div>-->
<!--            <lbtn size="large" type="primary" @click="doCargo" style="width: 100px;"> 装车</lbtn >-->
<!--          </div>-->
<!--          <div style="margin-top: 40px;">-->
<!--            <lbtn  size="large" @click="clearCargo" style="width: 100px;"> 清空</lbtn >-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--    &lt;!&ndash;    显示车辆&ndash;&gt;-->
<!--    <el-dialog close-on-press-escape destroy-on-close v-model="carsModal" :title="popTitle" :width="900">-->
<!--      <span class="area-item" :class="{active:popCurrent === car.name}"  v-for="(car, index) in cars" :key="index" @click="clickPopCar(car)">{{car.name}}</span>-->
<!--    </el-dialog>-->
<!--    &lt;!&ndash;    显示选择 驾驶员&ndash;&gt;-->
<!--    <el-dialog close-on-press-escape destroy-on-close v-model="driverModal" :title="popTitle" :width="900" :position="{top: 100}">-->
<!--      <div style="padding: 10px 0 20px 0;text-align: center;">-->
<!--        <el-checkbox  v-model="showDriver">驾驶员</el-checkbox>-->
<!--        <el-checkbox v-model="showDeliver"  style="margin-left: 30px;" >送货员</el-checkbox>-->
<!--      </div>-->
<!--      <span class="area-item" :class="{active:carModel.driverId === admin.id}"  v-for="(admin, index) in drivers" :key="index" @click="choseDriver(admin)">{{admin.name}}</span>-->
<!--    </el-dialog>-->
<!--    &lt;!&ndash;    显示选择 送货员&ndash;&gt;-->
<!--    <el-dialog close-on-press-escape destroy-on-close v-model="deliverModal" :title="popTitle" :width="900" :position="{top: 100}">-->
<!--      <div style="padding: 10px 0 20px 0;text-align: center;">-->
<!--        <el-checkbox  v-model="showDriver" >驾驶员</el-checkbox>-->
<!--        <el-checkbox v-model="showDeliver"  style="margin-left: 30px;" >送货员</el-checkbox>-->
<!--      </div>-->
<!--      <span class="area-item" :class="{active:carModel.deliverIds.indexOf(admin.id) !== -1}"  v-for="(admin, index) in drivers" :key="index" @click="choseDeliver(admin)">{{admin.name}}</span>-->
<!--      <div style="margin-top: 20px;text-align: center;padding: 10px 0 ;" >-->
<!--        <lbtn  @click="confirmDeliver" type="primary" style="width: 150px;" size="large">确定</lbtn >-->
<!--      </div>-->
<!--    </el-dialog>-->
<!--    <doprint ref="doPrintss" show-title :show-print-both="false" :show-print-bill="false" :show-print-add="true" @addNew="addNew" @hide="addNew"></doprint>-->
<!--    <el-dialog v-model="showBillPop" title="手工查询单据" close-on-press-escape destroy-on-close >-->
<!--      <div style="display: flex;">-->
<!--        <ltext v-model="billNo" placeholder="请输入销售单据号,可输入最末几位"></ltext>-->
<!--        <lbtn style="margin-left: 20px;" @click="doSearch" icon="search" >查询</lbtn>-->
<!--      </div>-->
<!--      <div style="margin-top: 30px;">-->
<!--        <div class="s-item" style="display: flex;" v-for="(item,index) in searchList" :key="index" @click="selectSearch(item.id)">-->
<!--          <div style="width: 120px;">{{item.billNo}}</div>-->
<!--          <div style="width: 100px;">{{item.billDate}}</div>-->
<!--          <div>{{item.buName}}</div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </el-dialog>-->
    <div>
      {{testVal}}
    </div>
  </div>
</template>
<script>
// 订单分配
import bus from "@/store/bus.js";
import Doprint from "@/views/deliver/doprint.vue";
import tool from "@/utils/tool";
import Lbtn from "../../lui/lbtn.vue";
export default {
  name: "cargoquick",
  components: {Lbtn,  Doprint},
  props: {
    centerPoint: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      area: {},
      showBillPop: false,
      columns: [
        {type: 'index', title: '', width: 50},
        {field: 'tenantName', title: '公司', width: 140},
        {field: 'areaName', title: '配送线路', width: 110, align: 'center'},
        {field: 'transTypeName', title: '类型', width: 100,align: 'center'},
        {field: 'billNo', title: '单据号', width: 130},
        {field: 'billDate', title: '票据日期', width: 100},
        {field: 'buName', title: '客户',width: 260,align: 'left'},
        {field: 'address', title: '地址', width: 260,align: 'left'},
        {field: '', title: '操作', width: 80,align: 'center',className: 'canClick',btns:[{id:'del',label:'删除',click: (row, rowIndex) => {
              this.orders.splice(rowIndex, 1)
              this.setCheckedOrders()
            }}]},
      ],
      orders: [],
      billNo: '', // 手工查询单据号
      searchList: [], // 手工查询出的列表
      //
      driverModal: false,
      deliverModal: false,
      showModal: false,
      title: '',
      height: window.innerHeight - 400,
      today: tool.getDay(),
      carList: [],
      carDomHeight: 0,
      grpColumns: [
        {type: 'index', width: 50,},
        {field: 'invName',title: '装车商品',width: 360,align: 'left' },
        {field: 'spec', title: '规格', width: 60,align: 'center'},
        {field: 'unit', title: '单位', width: 70,align: 'center'},
        {field: 'qty', title: '数量', width: 100,align: 'right',sum: true},
        {field: 'assQty', title: '辅助数量', width: 150,align: 'right'},
      ], // 商品汇总列
      grpData: [], // 商品汇总数据
      carModel: {
        licence: '',
        carsId: 0,
        driverId: 0,
        driverName: '',
        deliverIds: [],// 送货员ids
        deliverNames: '', // 送货员名 逗号分隔
      },
      currentCar:'',
      cargoAreas: '', // 订单中涉及的配送区域
      mergeCell: [],
      selectTab: 'tab1',
      unDeliverCargo: [], // 未配送单据
      deliverCargo: [], // 已配送的列表
      unWidth: window.innerWidth * 0.8,
      unHeight: window.innerHeight * 0.8,
      searchArr: [
        {field: 'cargoDate', title: '日期', type: 'date'},
        {field: 'licence', title: '车牌',idField: 'carsId', cat: 'carList', component: 'xcomb'},
        {field: 'driverName', title: '驾驶员',idField: 'driverId', cat: 'adminList', component: 'xcomb'},
        {field: 'deliverName', title: '送货员',idField: 'deliverId', cat: 'adminList', component: 'xcomb'},
        { align: 'center', itemRender:
              { name: '$buttons',
                children: [
                  { props: { type: 'submit', content: '搜索', status: 'primary',icon: 'fa fa-search' } },
                ]
              }
        }
      ],// 已送列表查询字段
      searchModel:{
        cargoDate: '',
        carsId: 0,
        licence: '',
        deliverId: 0,
        driverId: 0,
        deliverName: '',
      },
      popCurrent: '',
      carsModal: false, // 弹出 选择车辆
      adminsModal: false, // 弹出 选择人员
      popTitle: '', // 弹出 选择框的标题
      cars: [], // 车辆列表
      admins: [], // 人员列表
      currentFocusInput: '',
      showDriver: true,
      showDeliver: true,
      orderHeight: window.innerHeight - 340,
      testVal: ''
    }
  },
  created() {
    bus.$on('scan-ret', this.scanBillToCargoQuick)
  },
  unmounted () {
    bus.$off('scan-ret', this.scanBillToCargoQuick)
  },
  computed: {
    drivers () {
      let arr = []
      if (!this.showDeliver && !this.showDriver) {
        return this.admins
      }
      for (let i = 0; i < this.admins.length; i++) {
        if (this.showDriver && this.admins[i].roleName === '驾驶员') {
          arr.push(this.admins[i])
        }
        if (this.showDeliver && this.admins[i].roleName === '送货员') {
          arr.push(this.admins[i])
        }
      }
      return arr
    },
  },
  mounted() {
    tool.post('deliver/getArc',{}).then(ret => {
      if (ret.stat) {
        let data = ret.data
        this.cars = data.cars
        this.admins = data.admins
      }
    })
    window.ocr = this.doOcr
  },
  methods: {
    doOcr(params) {
      this.testVal = params
    },
    reload () {
      this.grpData = []
      this.orders = []
      this.carModel.licence = ''
      this.carModel.driverName = ''
      this.carModel.deliverNames = ''
      this.carModel.carsId = 0
      this.carModel.driverId = 0
      this.carModel.deliverIds = []
    },
    addNew () {
      this.reload()
    },
    scanBillToCargoQuick ({ code }) {
      let arr = code ? code.split('-') : []
      if (arr.length !== 2) {
        tool.err('二维码错误')
        return
      }
      if(arr[0] !== '180001') {
        let billId = arr[1]
        if ([150601,150602,150603].indexOf(arr[0]) !== -1) {
          return tool.err('非销售票据')
        }
        let repeatIndex =  tool.xe.findKey(this.orders,  item => item.id=== tool.xe.toNumber(billId))
        if(typeof repeatIndex === 'undefined') {
          this.clickArea( billId)
        }
        else {
          tool.suc('已存在')
        }
      }
      else {
        return tool.err('非销售票据')
      }
    },
    // 点击配送车辆信息等
    focusOn (type) {
      this.currentFocusInput = type
      if (type === 'carsId') {
        this.popTitle = '选择车辆'
        this.carsModal = true
      } else {
        if (this.currentFocusInput === 'driverId') {
          this.popTitle = '选择驾驶员'
          this.driverModal = true
        }
        if (this.currentFocusInput === 'deliverIds') {
          this.popTitle = '选择送货员 （可多选）'
          this.deliverModal = true
        }
      }
    },
    // 弹出选择车辆点击
    clickPopCar (car) {
      this.popCurrent = car.name
      this.carModel.licence = car.name
      this.carModel.carsId = car.id
      this.carsModal = false
    },
    // 选择驾驶员
    choseDriver (admin) {
      this.carModel.driverId = admin.id
      this.carModel.driverName = admin.name
      this.driverModal = false
    },
    // 选择送货员
    choseDeliver (admin) {
      let id = admin.id
      if (this.carModel.deliverIds.indexOf(id) === -1) {
        this.carModel.deliverIds.push(id)
      }
      else {
        for (let i = 0; i < this.carModel.deliverIds.length; i++) {
          if (this.carModel.deliverIds[i] === id) {
            this.carModel.deliverIds.splice(i, 1)
          }
        }
      }
    },
    // 确认送货员
    confirmDeliver () {
      if (this.carModel.deliverIds.length === 0) return tool.err('请选择至少 1 个送货员')
      this.adminsModal = false
      let names = []
      for (let i = 0; i < this.admins.length; i++) {
        let id = this.admins[i].id
        if(this.carModel.deliverIds.indexOf(id) !== -1) {
          names.push(this.admins[i].name)
        }
      }
      this.carModel.deliverNames = names.join(',')
      this.deliverModal = false
    },
    //
    clearInput (type) {
      if (type === 'carsId') {
        this.carModel.carsId = 0
        this.carModel.licence = ''
      }
      if (type === 'driverId') {
        this.carModel.driverId = 0
        this.carModel.driverName = ''
      }
      if (type === 'deliverIds') {
        this.carModel.deliverIds = []
        this.carModel.deliverNames = ''
      }
    },
    openSearch () {
      this.billNo = ''
      this.searchList = []
      this.showBillPop = true
    },
    doSearch () {
      if(this.billNo && this.billNo.trim()) {
        this.searchList = []
        tool.post('deliver/getBillByNo', {billNo: this.billNo}).then(ret => {
          if(ret.data.length === 0) {
            return tool.err('未找到数据')
          }
          this.searchList = ret.data
        })
      }
      else {
        tool.err('请输入单据号')
      }
    },
    selectSearch (id) {
      this.clickArea(id)
      this.billNo = ''
      this.showBillPop = false
      this.searchList = []
    },
    // 扫描一张单据查询
    clickArea (scanBillId = 0) {
      tool.post('deliver/getOrderByAreaId', {
        areaId: 0,
        beginDate: '',
        endDate: '',
        searchTxt: '',
        scanBillId: scanBillId
      }).then(ret => {
        if (ret.stat) {
          let data = ret.data
          let list = data.list
          let order = list[0]
          let repeat = false
          order.op = '删除'
          for (let i = 0; i < this.orders.length; i++) {
            if (this.orders[i].id === order.id) repeat = true
          }
          if (!repeat) this.orders.push(order)
          this.setCheckedOrders()
        }
      })
    },
    // 汇总票据的商品
    setCheckedOrders () {
      if (this.orders.length > 0) {
        let ids = []
        for (let i = 0; i < this.orders.length; i++) ids.push(this.orders[i].id)
        tool.post('deliver/grpOrders', {ids: ids}, false).then(ret => {
          if (ret.stat) {
            if (ret.data.length === 0) {
              this.grpData = []
              return
            }
            this.grpData = ret.data
          }
        })
      }
      else {
        this.grpData = []
      }
    },
    clearCargo () {
      tool.confirm('清除已选中的装车记录').then(() => {
        this.orders = []
        this.grpData = []
      })
    },
    // 装车
    doCargo () {
      if(!this.carModel.licence || !this.carModel.carsId) return tool.err('请选择车辆')
      if(!this.carModel.driverId || !this.carModel.driverName) return tool.err('请选择司机')
      if(!this.carModel.deliverIds.length === 0)  return tool.err('请选择送货员')
      if (this.orders.length === 0)  return tool.err('至少选择 1 条票据')
      let model = tool.xe.clone(this.carModel, true)
      let ids = []
      for (let i = 0; i < this.orders.length; i++) ids.push(this.orders[i].id)
      model.bills = ids
      model.areaId = this.area.id
      tool.confirm('确定装车', '装车提示').then(() => {
        tool.post('deliver/toCargo', model).then(ret => {
          if(ret.stat) {
            this.$refs.doPrintss.print(ret.data)
          }
        })
      })
    },
    cellStyle ({column}) {
      if (column.property === 'assQty') {
        return 'color: blue'
      }
    },
    // 所有车辆
    getCarList () {
      tool.post('deliver/carList', {}).then(ret => {
        this.carList = ret.data
      })
    },
    // 汇总单据中的商品
    groupGoods (checkedOrder) {
      let goods = []
      this.grpData = []
      for (let i = 0; i < checkedOrder.length; i++) {
        goods = goods.concat(checkedOrder[i].data)
      }
      let grpGoods = tool.xe.groupBy(goods, 'invId')
      let ret = []
      for (let i in grpGoods) {
        let g = grpGoods[i][0]
        let total = tool.xe.sum(grpGoods[i], item => tool.multiply(item.calNum, item.qty))
        let assQty = this.getAss(total, g)
        ret.push({invName: g.invName, spec: g.spec, unit: g.unit, assQty: assQty,})
      }
      return ret
    },
    // 小单位算成辅助单位
    getAss (qty, row) {
      let spec = row.spec
      if (!spec) {
        tool.err(row.invName +' 规格换算不能为0')
        return
      }
      let mainQty = (qty - (qty%spec)) / spec
      let rqty = qty%spec
      let ass = ''
      if (mainQty) {
        ass = ass + mainQty +' ' + row.unit1 + ' '
      }
      if (rqty) {
        ass = ass + rqty +' ' + row.unit2
      }
      return ass
    },
  }
}
</script>

<style scoped>
.title {
  text-align: center;
  font-weight: bold;
  font-size: 22px;
  background-color: #01aaee;
  color: white;
  height: 40px;
  line-height: 40px;
}
.area-item {
  display: inline-block;
  border: 1px solid gainsboro;
  background-color: #f8f8f9;
  margin: 5px;
  height: 50px;
  line-height: 50px;
  width: 130px;
  text-align: center;
  border-radius: 2px;
  font-weight: bold;
  cursor: pointer;
  color: #515a6e;
  white-space: nowrap;
  overflow: hidden;
}
.s-item {
  border-bottom: 1px solid #F2F2F2;
  padding: 5px 0 ;
  margin-bottom: 10px;
}
.area-item.active {
  border: 1px solid #5cadff;
  background-color: #5cadff;
  color: white;
}

.undeliver tr:hover {
  background-color: #f8f8f9;
}
.pd2{
  padding: 2px;
}
.grid td {padding-left: 2px;}
.order {
}
.br{
  border-right: 1px solid #dedede;
}
.order .grid td {
  /*background-color: white;*/
}
.bb{
  border-bottom: 1px solid #dedede;
}
.bt{
  border-top: 1px solid #dedede;
}
.bl{
  border-left: 1px solid #dedede;
}
.tc {
  text-align: center;
}
.tr {
  text-align: right;
}
.order td,.order th {
  height: 30px;
  line-height: 30px;
}
.order td {
  color: #2b85e4;
}
.order .grid tr{
  /*background-color: white;*/
}
.order .grid tr:hover{
  background-color: gainsboro;
}
.grid tr {
  /*background-color: white;*/
}
.order td i {

}
.order td i:hover {
  cursor: pointer;
  color: red;
}
.undeliver {
}
.undeliver th {
  padding: 5px 3px;
}
.undeliver td {
  padding: 5px 3px;
}
li {margin-top: 10px;}
.orow:hover,.orow:active{background-color: #2db7f5;color: white;}
</style>
